#include <Adafruit_NeoPixel.h>
#include <WiFiManager.h>
#include <TimeLib.h>
#include <NtpClientLib.h>
#include <SimpleTimer.h>
#define PIN 12
#define NUMPIXELS 84
WiFiServer server(80);
SimpleTimer timer;
int8_t timeZone = 8, hour_H, hour_L, min_H, min_L, sec, minutes, hours;
const PROGMEM char *ntpServer = "ntp1.aliyun.com";
Adafruit_NeoPixel pixels(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);
byte brightness = 5;
byte segGroups[7][4] = {
  // right (seen from front) digit
  {5, 6, 7, 8 }, // top, a
  {8, 9, 10, 11 }, // top right, b
  { 11, 12, 13, 14 }, // bottom right, c
  {14, 15, 16, 17 }, // bottom, d
  {17, 18, 19, 2 }, // bottom left, e
  {2, 3, 4, 5 }, // top left, f
  {0, 1, 2, 11 }, // center, g};
};

byte digits[10][20] = {
  { 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, //0
  { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0}, //1
  { 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1}, //2
  { 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0}, //3
  { 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0}, //4
  { 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0}, //5
  { 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1}, //6
  { 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0}, //7
  { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, //8
  { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0} //9
};

void setup() {
  Serial.begin(9600);
  pixels.begin(); // INITIALIZE NeoPixel strip object (REQUIRED)
  pixels.setBrightness(brightness);
  WiFi.mode(WIFI_STA);
  WiFiManager wm;
  bool res;
  res = wm.autoConnect();
  NTP.setInterval (600);
  NTP.setNTPTimeout (1500);
  NTP.begin (ntpServer, timeZone, false);
  timer.setInterval(1000L, Simple_timer_1);
  show_minute();
  show_hour();
}
void show_minute()
{
  minutes = NTP.getTimeMinute();
  min_H = minutes / 10;
  min_L = minutes % 10;
  showDigit(min_H, 0xff0000, 2);
  showDigit(min_L, 0xff0000, 3);
}
void show_hour()
{
  hours = NTP.getTimeHour24();
  hour_H = hours / 10;
  hour_L = hours % 10;


  showDigit(hour_H, 0xff0000, 0);
  showDigit(hour_L, 0xff0000, 1);
}
void showDigit(byte digit, int color, byte segDisplay) {
  for (byte i = 0; i < 20; i++) {
    if (digits[digit][i] == 0) {
      pixels.setPixelColor(i + segDisplay * 20 + int(segDisplay / 2) * 4, 0);
    }
    else
      pixels.setPixelColor(i + segDisplay * 20 + int(segDisplay / 2) * 4, color);
  }
}
void Simple_timer_1() {
  sec = NTP.getTimeSecond();
  show_minute();
  show_hour();
  if (sec % 2)
    for (int j = 40; j < 44; j++)
      pixels.setPixelColor(j, 0);
  else
    for (int j = 40; j < 44; j++)
      pixels.setPixelColor(j, 0xff0000);

  pixels.show();
}
void loop() {
  timer.run();
}
